//
//  JoinRoomPopViewController.m
//  Fangmm
//
//  Created by ChaoZhou on 16/3/2.
//  Copyright © 2016年 com.fangmm. All rights reserved.
//

#import "JoinRoomPopViewController.h"
#import "BecomeRoomChiefViewController.h"
#import "CheckSelfMessageViewController.h"
#import "UserHomepageViewController.h"

#import "RoomChiefListTableViewCell.h"
#import "RoomChiefTitleTableViewCell.h"
#import "HouseTitleTableViewCell.h"

#import "JoinRoomBottomView.h"

#import <SDWebImage/UIImageView+WebCache.h>
#import <SDWebImage/UIButton+WebCache.h>
#import <TSMessages/TSMessageView.h>
#import "ACMacros.h"

#import "Seat.h"
#import "Team.h"
#import "HttpServer.h"

@interface JoinRoomPopViewController () <UITableViewDataSource, UITableViewDelegate, RoomChiefListTableViewCellDelegate>

@end

@implementation JoinRoomPopViewController {
    UIView *bottom;
    NSMutableArray *teams;
    NSString *selectSeatId;
    NSString *selectTeamId;
    
    NSInteger selectedRow;
    NSInteger selectedButtonTag;
    UIButton *chooseRoomButton;
    JoinRoomBottomView *joinBottom;
    NSString *tips;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self insertBackground];
    [self configureTableView];
    [self configureBottomView];
    [self loadTeamTips];
    selectedRow = -1;
    selectedButtonTag = -1;

    // Do any additional setup after loading the view from its nib.
}

- (void)viewWillAppear:(BOOL)animated {
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
}

- (void)viewWillDisappear:(BOOL)animated {
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
#pragma mark - Configuring the view’s layout behavior
- (void)insertBackground {
    UIImageView *backgroundImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, Main_Screen_Width, Main_Screen_Height)];
    [backgroundImageView setImage:[UIImage imageNamed:@"screen_bg"]];
    [self.view insertSubview:backgroundImageView atIndex:0];
}

- (void)configureTableView {
    [self.tableView setDelegate:self];
    [self.tableView setDataSource:self];
    [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [self.tableView registerNib:[UINib nibWithNibName:@"HouseTitleTableViewCell" bundle:nil] forCellReuseIdentifier:@"HouseTitleTableViewCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"RoomChiefTitleTableViewCell" bundle:nil] forCellReuseIdentifier:@"RoomChiefTitleTableViewCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"RoomChiefListTableViewCell" bundle:nil] forCellReuseIdentifier:@"RoomChiefListTableViewCell"];
}

- (void)configureBottomView {
    chooseRoomButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, Main_Screen_Width, 50)];
    [self.bottomView addSubview:chooseRoomButton];
    [chooseRoomButton setBackgroundColor:RGBACOLOR(255, 118, 108, 1)];
    [chooseRoomButton setTitle:@"请选择要加入的房间" forState:UIControlStateNormal];
    [chooseRoomButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [chooseRoomButton.titleLabel setFont:[UIFont systemFontOfSize:15]];
}


#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    switch (section) {
        case 0:
            return 2;
            break;
        case 1:
            teams = self.teamsData;
            if (teams.count == 0) {
                return 1;
            } else {
                return teams.count;
            }
            break;

        default:
            return 0;
            break;
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger section = indexPath.section;
    NSInteger row = indexPath.row;
    UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    switch (section) {
        case 0:
        {
            switch (row) {
                case 0:
                {
                    HouseTitleTableViewCell *titleCell = [tableView dequeueReusableCellWithIdentifier:@"HouseTitleTableViewCell"];
                    [titleCell setSelectionStyle:UITableViewCellSelectionStyleNone];
                    titleCell.topLine.hidden = true;
                    [titleCell setBackgroundColor:[UIColor clearColor]];
                    [titleCell.housePriceLabel setHidden:true];
                    [titleCell.houseMessage sd_setImageWithURL:[NSURL URLWithString:self.house.cover]];
                    [titleCell.houseNameLabel setText:self.house.community];
                    [titleCell.houseRegionLabel setText:self.house.region];
                    [titleCell.houseNumLabel setText:[NSString stringWithFormat:@" %d室%d厅%d卫",self.house.roomNum, self.house.hallNum, self.house.toiletNum]];
                    [titleCell.houseAreaLabel setText:[NSString stringWithFormat:@" %dm²", self.house.area]];
                    [titleCell.roomChiefNumLabel setText:[NSString stringWithFormat:@"库存%d个室长",teams.count]];
                    CGFloat originX = titleCell.housePriceLabel.frame.origin.x;
                    CGFloat originY = titleCell.housePriceLabel.frame.origin.y;
                    UIButton *wholeRentButton = [[UIButton alloc]initWithFrame:CGRectMake(originX, originY, 40, 20)];
                    [wholeRentButton.layer setCornerRadius:10];
                    [wholeRentButton setBackgroundColor:RGBACOLOR(255, 118, 108, 1)];
                    [wholeRentButton setTitle:@"整租" forState:UIControlStateNormal];
                    [wholeRentButton.titleLabel setFont:[UIFont systemFontOfSize:12]];
                    [titleCell addSubview:wholeRentButton];
                    [wholeRentButton addTarget:self action:@selector(clickToWholeRent) forControlEvents:UIControlEventTouchUpInside];
                    NSArray *array = @[titleCell.housePriceLabel, titleCell.houseNameLabel, titleCell.houseNumLabel, titleCell.houseAreaLabel, titleCell.houseRegionLabel, titleCell.roomChiefNumLabel];
                    for (UILabel *label in array) {
                        [label setTextColor:[UIColor whiteColor]];
                    }
                    return titleCell;
                }
                    break;
                default:
                {
                    UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
                    [cell setBackgroundColor:[UIColor clearColor]];
                    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
                    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(15, 9, Main_Screen_Width - 80, 11)];
                    [label setText:tips];
                    [label setTextColor:[UIColor whiteColor]];
                    [label setFont:[UIFont systemFontOfSize:10]];
                    [cell addSubview:label];
                    return cell;
                }
                    break;
            }
        }
            break;
        case 1:
            if (teams.count != 0) {
                teams = self.teamsData;
                NSInteger row = indexPath.row;
                Team *team = [[Team alloc]initWithDic:teams[row]];
                NSArray *seats = team.seats;
                RoomChiefListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RoomChiefListTableViewCell"];
                cell.delegate = self;
                UIView *line = [[UIView alloc]initWithFrame:CGRectMake(10, 104.3, Main_Screen_Width - 20, 0.7)];
                [line setBackgroundColor:RGBACOLOR(240, 240, 240, 0.8)];
                [cell addSubview:line];
                cell.team = team;
                cell.tag = row;
                [self actionTimer:cell];
                [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
                [cell.numberLabel setText:[NSString stringWithFormat:@"%ld.",row + 1]];
                [cell.aNameLabel setTextColor:[UIColor whiteColor]];
                [cell.bNameLabel setTextColor:[UIColor whiteColor]];
                [cell.cNameLabel setTextColor:[UIColor whiteColor]];
                [cell setBackgroundColor:[UIColor clearColor]];
                [cell.aChooseButton setHidden:true];
                [cell.bChooseButton setHidden:true];
                [cell.cChooseButton setHidden:true];
                for (int i = 0; i < seats.count; i++) {
                    Seat *seat = [[Seat alloc]initWithDic:seats[i]];
                    switch (i) {
                        case 0:
                            [cell.aChooseButton setHidden:false];
                            if (!(seat.userId == nil || [seat.userId isEqual:@""])) {
                                [cell.aAvatarButton sd_setBackgroundImageWithURL:[NSURL URLWithString:seat.userAvatar] forState:UIControlStateNormal];
                                if (seat.leader) {
                                    [cell.aChooseButton setTitle:@"室长" forState:UIControlStateNormal];
                                    [cell.aChooseButton setTitleColor:RGBACOLOR(255, 118, 108, 1) forState:UIControlStateNormal];
                                } else {
                                    [cell.aChooseButton setTitle:@"室友" forState:UIControlStateNormal];
                                    [cell.aChooseButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
                                    [cell.aChooseButton.layer setBorderColor:[[UIColor whiteColor] CGColor]];
                                }
                                [cell.aNameLabel setText:seat.userName];
                                if ([seat.userGender isEqual:@"f"]) {
                                    [cell.aGenderImageView setImage:[UIImage imageNamed:@"girl_22-22"]];
                                } else {
                                    [cell.aGenderImageView setImage:[UIImage imageNamed:@"boy_22-22"]];
                                }
                                cell.aPriceLabel.hidden = true;
                            } else {
                                cell.aPriceLabel.hidden = false;
                                [cell.aPriceLabel setText:[NSString stringWithFormat:@"%d元/月",seat.rent]];
                                [cell.aChooseButton setTitle:@"选择" forState:UIControlStateNormal];
                                [cell.aChooseButton setBackgroundColor:RGBACOLOR(255, 255, 255, 0.6)];
                                [cell.aChooseButton.layer setBorderColor:[[UIColor clearColor] CGColor]];
                                [cell.aChooseButton setTitleColor:RGBCOLOR(255, 118, 108) forState:UIControlStateNormal];
                            }
                            break;
                        case 1:
                            [cell.bChooseButton setHidden:false];
                            if (!(seat.userId == nil || [seat.userId isEqual:@""])) {
                                [cell.bAvatarButton sd_setBackgroundImageWithURL:[NSURL URLWithString:seat.userAvatar] forState:UIControlStateNormal];
                                if (seat.leader) {
                                    [cell.bChooseButton setTitle:@"室长" forState:UIControlStateNormal];
                                    [cell.bChooseButton setTitleColor:RGBACOLOR(255, 118, 108, 1) forState:UIControlStateNormal];
                                } else {
                                    [cell.bChooseButton setTitle:@"室友" forState:UIControlStateNormal];
                                    [cell.bChooseButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
                                    [cell.bChooseButton.layer setBorderColor:[[UIColor whiteColor] CGColor]];
                                }
                                [cell.bNameLabel setText:seat.userName];
                                if ([seat.userGender isEqual:@"f"]) {
                                    [cell.bGenderImageView setImage:[UIImage imageNamed:@"girl_22-22"]];
                                } else {
                                    [cell.bGenderImageView setImage:[UIImage imageNamed:@"boy_22-22"]];
                                }
                                cell.bPriceLabel.hidden = true;
                            } else {
                                cell.bPriceLabel.hidden = false;
                                [cell.bPriceLabel setText:[NSString stringWithFormat:@"%d元/月",seat.rent]];
                                [cell.bChooseButton setTitle:@"选择" forState:UIControlStateNormal];
                                [cell.bChooseButton setBackgroundColor:RGBACOLOR(255, 255, 255, 0.6)];
                                [cell.bChooseButton.layer setBorderColor:[[UIColor clearColor] CGColor]];
                                [cell.bChooseButton setTitleColor:RGBCOLOR(255, 118, 108) forState:UIControlStateNormal];
                            }
                            break;
                        case 2:
                            [cell.cChooseButton setHidden:false];
                            if (!(seat.userId == nil || [seat.userId isEqual:@""])) {
                                [cell.cAvatarButton sd_setBackgroundImageWithURL:[NSURL URLWithString:seat.userAvatar] forState:UIControlStateNormal];
                                if (seat.leader) {
                                    [cell.cChooseButton setTitle:@"室长" forState:UIControlStateNormal];
                                    [cell.cChooseButton setTitleColor:RGBACOLOR(255, 118, 108, 1) forState:UIControlStateNormal];
                                } else {
                                    [cell.cChooseButton setTitle:@"室友" forState:UIControlStateNormal];
                                    [cell.cChooseButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
                                    [cell.cChooseButton.layer setBorderColor:[[UIColor whiteColor] CGColor]];
                                }
                                [cell.cNameLabel setText:seat.userName];
                                if ([seat.userGender isEqual:@"f"]) {
                                    [cell.cGenderImageView setImage:[UIImage imageNamed:@"girl_22-22"]];
                                } else {
                                    [cell.cGenderImageView setImage:[UIImage imageNamed:@"boy_22-22"]];
                                }
                                cell.cPriceLabel.hidden = true;
                            } else {
                                cell.cPriceLabel.hidden = false;
                                [cell.cPriceLabel setText:[NSString stringWithFormat:@"%d元/月",seat.rent]];
                                [cell.cChooseButton setTitle:@"选择" forState:UIControlStateNormal];
                                [cell.cChooseButton setBackgroundColor:RGBACOLOR(255, 255, 255, 0.6)];
                                [cell.cChooseButton.layer setBorderColor:[[UIColor clearColor] CGColor]];
                                [cell.cChooseButton setTitleColor:RGBCOLOR(255, 118, 108) forState:UIControlStateNormal];
                            }
                            break;
                        default:
                            break;
                    }
                }
                return cell;
            } else {
                UITableViewCell *emptyCell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"emptyCell"];
                [emptyCell setSelectionStyle:UITableViewCellSelectionStyleNone];
                [emptyCell setBackgroundColor:[UIColor clearColor]];
                [emptyCell.textLabel setText:@"暂无室友小组,快来成为室长创建小组吧!"];
                [emptyCell.textLabel setTextColor:[UIColor whiteColor]];
                [emptyCell.textLabel setFont:[UIFont systemFontOfSize:15]];
                return emptyCell;
            }
            break;
  
        default:
            return cell;
            break;
    }
}

#pragma mark - Table view delegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger section = indexPath.section;
    NSInteger row = indexPath.row;
    switch (section) {
        case 0:
            switch (row) {
                case 0:
                    return 130;
                    break;
                    
                default:
                    return 30;
                    break;
            }
            break;
        case 1:
            return 105;
        default:
            return 0;
            break;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 1) {
        return 55;
    } else {
        return 0.1;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *header = [[UIView alloc]init];
    [header setBackgroundColor:[UIColor clearColor]];
    if (section == 1) {
        RoomChiefTitleTableViewCell *roomChiefTitleCell = [tableView dequeueReusableCellWithIdentifier:@"RoomChiefTitleTableViewCell"];
        [roomChiefTitleCell setFrame:CGRectMake(0, 0, Main_Screen_Width, 55)];
        [roomChiefTitleCell setSelectionStyle:UITableViewCellSelectionStyleNone];
        roomChiefTitleCell.sectionHeaderHeight.constant = 0;
        roomChiefTitleCell.sectionHeaderTitleView.hidden = true;
        [roomChiefTitleCell.roomALabel setTextColor:[UIColor whiteColor]];
        [roomChiefTitleCell.roomBLabel setTextColor:[UIColor whiteColor]];
        [roomChiefTitleCell.roomCLabel setTextColor:[UIColor whiteColor]];
        [roomChiefTitleCell.clockImage setImage:[UIImage imageNamed:@"detail_time_f"]];
        [roomChiefTitleCell setBackgroundColor:[UIColor clearColor]];
//        UIView *line = [[UIView alloc]initWithFrame:CGRectMake(10, 50.5, Main_Screen_Width - 20, 0.5)];
//        [line setBackgroundColor:RGBACOLOR(240, 240, 240, 0.5)];
//        [roomChiefTitleCell addSubview:line];
        [roomChiefTitleCell.roomALabel setHidden:true];
        [roomChiefTitleCell.roomBLabel setHidden:true];
        [roomChiefTitleCell.roomCLabel setHidden:true];
        for (int i = 0; i < self.house.rooms.count; i++) {
            switch (i) {
                case 0:
                    [roomChiefTitleCell.roomALabel setHidden:false];
                    break;
                case 1:
                    [roomChiefTitleCell.roomBLabel setHidden:false];
                    break;
                case 2:
                    [roomChiefTitleCell.roomCLabel setHidden:false];
                    break;
                    
                default:
                    break;
            }
        }
        [header addSubview:roomChiefTitleCell];
    }
    return header;

}
#pragma mark - Room chief list delegate
- (void)clickToChooseRoom:(NSString *)roomName WithSeatId:(NSString *)seatId InTeam:(NSString *)teamId WithRent:(int)rent {
    selectSeatId = seatId;
    selectTeamId = teamId;
    if (!joinBottom) {
        joinBottom = [[JoinRoomBottomView alloc]init];
        joinBottom = [[[NSBundle mainBundle]loadNibNamed:@"JoinRoomBottomView" owner:self options:nil] firstObject];
        [joinBottom setFrame:CGRectMake(0, 0, Main_Screen_Width, 50)];
        [joinBottom.commitButton addTarget:self action:@selector(clickToJoinRoom) forControlEvents:UIControlEventTouchUpInside];
    }
    if (![[self.bottomView subviews]containsObject:joinBottom]) {
        [self.bottomView addSubview:joinBottom];
    }
    
    [joinBottom.bottomInfoButton setTitle:roomName forState:UIControlStateNormal];
    [joinBottom.rentButton setTitle:[NSString stringWithFormat:@"¥%d",rent] forState:UIControlStateNormal];
}

- (void)clickToShowUserMainInfoWithTag:(NSInteger)tag WithIndex:(NSInteger)index {
    Team *team = [[Team alloc]initWithDic:teams[index]];
    Seat *seat = [[Seat alloc]initWithDic:team.seats[tag]];
    UserHomepageViewController *userHomepageVC = [[UserHomepageViewController alloc]init];
    userHomepageVC.userId = seat.userId;
    userHomepageVC.userName = seat.userName;
    [self.navigationController pushViewController:userHomepageVC animated:true];
}


- (void)clickToWholeRent {
    if (!joinBottom) {
        joinBottom = [[JoinRoomBottomView alloc]init];
        joinBottom = [[[NSBundle mainBundle]loadNibNamed:@"JoinRoomBottomView" owner:self options:nil] firstObject];
        [joinBottom setFrame:CGRectMake(0, 0, Main_Screen_Width, 50)];
    }
    if (![[self.bottomView subviews]containsObject:joinBottom]) {
        [self.bottomView addSubview:joinBottom];
    }
    [joinBottom.commitButton addTarget:self action:@selector(requestToWholeRent) forControlEvents:UIControlEventTouchUpInside];
    [joinBottom.bottomInfoButton setTitle:@"整租" forState:UIControlStateNormal];
    
    [joinBottom.rentButton setTitle:[NSString stringWithFormat:@"¥%d",self.house.rent] forState:UIControlStateNormal];
}

- (void)clickToJoinRoom {
    [self requestToJoinTeamWithTeamId:selectTeamId andSeatId:selectSeatId];
}

- (IBAction)clickToRoomChiefView:(UIButton *)sender {
    BecomeRoomChiefViewController *becomeRoomChiefVC = [[BecomeRoomChiefViewController alloc]initWithNibName:@"BecomeRoomChiefViewController" bundle:nil];
    becomeRoomChiefVC.house = self.house;
    UINavigationController *roomChiefNav = [[UINavigationController alloc]initWithRootViewController:becomeRoomChiefVC];
    [self presentViewController:roomChiefNav animated:true completion:^{
    }];
}

- (IBAction)clickToCancelPop:(UIButton *)sender {
    [self dismissViewControllerAnimated:true completion:^{
        
    }];
}

- (void)requestToJoinTeamWithTeamId:(NSString *)teamId andSeatId:(NSString *)seatId {
    [HttpServer postToJoinTeam:teamId WithSeatId:seatId WithSuccessBlock:^(NSDictionary *successDic) {
        CheckSelfMessageViewController *checkSelfVC = [[CheckSelfMessageViewController alloc]initWithNibName:@"CheckSelfMessageViewController" bundle:nil];
        checkSelfVC.passingType = @"join";
        UINavigationController *joinRoomNav = [[UINavigationController alloc]initWithRootViewController:checkSelfVC];
        [self presentViewController:joinRoomNav animated:true completion:^{
        }];

    } withFailBlock:^(id failData) {
        NSLog(@"%@",failData);
        if ([[failData allKeys]containsObject:@"msg"]) {
            NSString *failString = [failData objectForKey:@"msg"];
            [TSMessage showNotificationInViewController:self title:@"申请失败!" subtitle:failString type:TSMessageNotificationTypeWarning duration:1.0];
        } else {
            [TSMessage showNotificationInViewController:self title:@"申请失败!" subtitle:@"请稍后重试" type:TSMessageNotificationTypeWarning duration:1.0];
        }
        
    }];
}

- (void)requestToWholeRent {
    [HttpServer postToCreateTeamWithHouseId:self.house.houseId AndOffers:@"" WithSuccessBlock:^(NSDictionary *successDic) {
        NSString *successTeamId = [successDic objectForKey:@"teamId"];
        [self dismissViewControllerAnimated:true completion:^{
            
        }];
    } withFailBlock:^(id failData) {
        NSLog(@"%@",failData);
        if ([[failData allKeys] containsObject:@"msg"]) {
            [TSMessage showNotificationInViewController:self title:[NSString stringWithFormat:@"%@",[failData objectForKey:@"msg"]] subtitle:@"请稍后重试" type:TSMessageNotificationTypeError duration:2.0 canBeDismissedByUser:true];
        } else {
            [TSMessage showNotificationInViewController:self title:@"请求出错!" subtitle:@"请稍后重试" type:TSMessageNotificationTypeError duration:2.0 canBeDismissedByUser:true];
        }
    }];

}

- (void)selectedSeatWithSeatId:(NSString *)seatId TeamId:(NSString *)teamId RoomName:(NSString *)roomName AndRent:(int)rent {
    selectSeatId = seatId;
    selectTeamId = teamId;
    if (!joinBottom) {
        joinBottom = [[JoinRoomBottomView alloc]init];
        joinBottom = [[[NSBundle mainBundle]loadNibNamed:@"JoinRoomBottomView" owner:self options:nil] firstObject];
        [joinBottom setFrame:CGRectMake(0, 0, Main_Screen_Width, 50)];
        [joinBottom.commitButton addTarget:self action:@selector(clickToJoinRoom) forControlEvents:UIControlEventTouchUpInside];
    }
    if (![[self.bottomView subviews]containsObject:joinBottom]) {
        [self.bottomView addSubview:joinBottom];
    }
    
    [joinBottom.bottomInfoButton setTitle:roomName forState:UIControlStateNormal];
    [joinBottom.rentButton setTitle:[NSString stringWithFormat:@"¥%d",rent] forState:UIControlStateNormal];
}

- (void)clickButton:(UIButton *)sender Index:(NSInteger)index ButtonTag:(NSInteger)buttontag {
    RoomChiefListTableViewCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:selectedRow inSection:1]];
    if (selectedButtonTag == 0) {
        [cell.aChooseButton setTitle:@"选择" forState:UIControlStateNormal];
        [cell.aChooseButton setBackgroundColor:RGBACOLOR(255, 255, 255, 0.7)];
        [cell.aChooseButton.layer setBorderColor:[[UIColor clearColor] CGColor]];
        [cell.aChooseButton setTitleColor:RGBCOLOR(255, 118, 108) forState:UIControlStateNormal];
    } else if (selectedButtonTag == 1) {
        [cell.bChooseButton setTitle:@"选择" forState:UIControlStateNormal];
        [cell.bChooseButton setBackgroundColor:RGBACOLOR(255, 255, 255, 0.7)];
        [cell.bChooseButton.layer setBorderColor:[[UIColor clearColor] CGColor]];
        [cell.bChooseButton setTitleColor:RGBCOLOR(255, 118, 108) forState:UIControlStateNormal];
    } else {
        [cell.cChooseButton setTitle:@"选择" forState:UIControlStateNormal];
        [cell.cChooseButton setBackgroundColor:RGBACOLOR(255, 255, 255, 0.7)];
        [cell.cChooseButton.layer setBorderColor:[[UIColor clearColor] CGColor]];
        [cell.cChooseButton setTitleColor:RGBCOLOR(255, 118, 108) forState:UIControlStateNormal];
    }
    selectedRow = index;
    selectedButtonTag = buttontag;
    RoomChiefListTableViewCell *selectcell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:index inSection:1]];
    if (buttontag == 0) {
        [selectcell.aChooseButton setTitle:@"已选" forState:UIControlStateNormal];
        [selectcell.aChooseButton setBackgroundColor:RGBACOLOR(255, 118, 108, 1)];
        [selectcell.aChooseButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    } else if (buttontag == 1) {
        [selectcell.bChooseButton setTitle:@"已选" forState:UIControlStateNormal];
        [selectcell.bChooseButton setBackgroundColor:RGBACOLOR(255, 118, 108, 1)];
        [selectcell.bChooseButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    } else {
        [selectcell.cChooseButton setTitle:@"已选" forState:UIControlStateNormal];
        [selectcell.cChooseButton setBackgroundColor:RGBACOLOR(255, 118, 108, 1)];
        [selectcell.cChooseButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    }
}

#pragma mark - Timer methods
- (void)actionTimer:(RoomChiefListTableViewCell *)cell {
    Team *team = cell.team;
    NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    NSDate *expireDate = [dateFormatter dateFromString:team.expireTime];
    NSDate *startDate = [NSDate date];
    NSTimeInterval timeInterval =[expireDate timeIntervalSinceDate:startDate];
    
    dispatch_source_t _timer;
    if (_timer==nil) {
        __block int timeout = timeInterval; //倒计时时间
        
        if (timeout!=0) {
            dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
            _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
            dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
            dispatch_source_set_event_handler(_timer, ^{
                if(timeout<=0){ //倒计时结束，关闭
                    dispatch_source_cancel(_timer);
                    //                    _timer = nil;
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [cell.timeLabel setText:@"报价已失效"];
                        //                        self.dayLabel.text = @"";
                        //                        self.hourLabel.text = @"00";
                        //                        self.minuteLabel.text = @"00";
                        //                        self.secondLabel.text = @"00";
                    });
                }else{
                    int days = (int)(timeout/(3600*24));
                    //                    if (days==0) {
                    //                        self.dayLabel.text = @"";
                    //                    }
                    int hours = (int)((timeout-days*24*3600)/3600);
                    int minute = (int)(timeout-days*24*3600-hours*3600)/60;
                    int second = timeout-days*24*3600-hours*3600-minute*60;
                    dispatch_async(dispatch_get_main_queue(), ^{
                        if (days == 0) {
                            [cell.timeLabel setText:[NSString stringWithFormat:@"%d时%d分%d秒后报价失效",hours, minute, second]];
                            if (hours == 0) {
                                [cell.timeLabel setText:[NSString stringWithFormat:@"%d分%d秒后报价失效",minute, second]];
                                if (minute == 0) {
                                    [cell.timeLabel setText:[NSString stringWithFormat:@"%d秒后报价失效", second]];
                                }
                            }
                        }else{
                            [cell.timeLabel setText:[NSString stringWithFormat:@"%d天%d时%d分%d秒后报价失效",days, hours, minute, second]];
                        }
                    });
                    timeout--;
                }
            });
            dispatch_resume(_timer);
        }
    }
    
}

#pragma mark - Network methods
- (void)loadTeamTips {
    [HttpServer getTeamTipsWithHouseId:self.house.houseId withSuccessBlock:^(NSDictionary *successDic) {
        tips = [NSString stringWithFormat:@"%@",[successDic objectForKey:@"tip"]];
        [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:1 inSection:0]] withRowAnimation:UITableViewRowAnimationAutomatic];
    } withFailedBlock:^(id failData) {
        tips = @"你还未对该房源申请过报价，哦，赶快报价吧。";
        [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:1 inSection:0]] withRowAnimation:UITableViewRowAnimationAutomatic];
    }];
}

@end
